# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  # 格式化时间
  def format_time(time,format=:date,timezone=0)
    return '' if time.blank? 
    case format
      when :date
        timezone.hours.since(time).strftime "%d-%m-%Y"
      when :datetime
        #time.strftime "%d-%m-%Y %H:%M %Z"
        time - Time.now < 0 ? "assessing results..." : "starts in " + distance_of_time_in_words(time,Time.now.utc).gsub(' mins','mins').gsub(' hrs','hrs')
      when :db
        time.to_formatted_s :db
      else
        'unknown time'
    end
  end

  # 对对象进行时间分组
  def group_by_time(objects,options={})
    options[:attr] ||= "created_at"
    options[:order] ||= "asc"
    grouped_objects = {}
    last_time = nil
    objects.each do |object|
      object_time = object.send(options[:attr]).to_date
      last_time = object_time.strftime("%Y%m%d")
      grouped_objects[last_time] ||= []
      grouped_objects[last_time] << object
    end
    if block_given?
      keys = grouped_objects.keys.sort
      keys.reverse if options[:order] =~ /^desc$/i
      keys.each do |time|
        objs = grouped_objects[time]
        yield DateTime.parse(time),objs
      end
    else
      grouped_objects
    end
  end

  # 产生一个tab item
  # 当传递的参数为 字符串
  # 则当action 等于 字符串的时候，TAB选中
  # 当参数为 符号
  # 则当controller跟符号相等，TAB选中
  # 当参数为数组，头一个是controller,末一个是action
  # 两个都相等的话，则tab选中
  # 当参数为hash，则hash中的数据匹配params中的数据的时候，tab选中
  # 比如
  # link_to_tab "edit","test","url" #当params[:action] 为 "edit"的时候，选中
  # 其他的以此类推
  # 也可以设置多个action数值 比如 link_to_tab "index,edit","text",url
  # 它将会在params[:action] 为 "index" 或者为 "edit" 的时候被选中
  # 当selected为 proc 的时候,会执行该proc并使用返回的数据来决定是否选中
  def link_to_tab(selected,text,url="",options={},&block)
    options = {}.merge(options)
    controller = params[:controller].gsub("/","_")
    case selected
      when String
        s = selected.split(",").include?(params[:action])
      when Array
        s = controller == selected.first && selected.last.split(",").include?(params[:action])
      when Symbol
        s = controller == selected.to_s
      when Hash
        s = true
        selected.keys.each do |i|
          if params[i] != selected[i]
            s = false
            break
          end
        end
        url = url_for(selected)
      when Proc
        s = selected.call
      else
        s = selected
    end

    if s
      r = fb_tab_item(text,url,options.merge(:selected=>true))
    else
      r = fb_tab_item(text,url,options.merge(:selected=>false))
    end
    
    if block_given?
      concat(r)
      concat(capture(&block)) if s
    else
      r
    end
  end


  def tab_item(selected,text,url="",options={},&block)
    options = {}.merge(options)
    controller = params[:controller].gsub("/","_")
    case selected
      when String
        s = selected.split(",").include?(params[:action])
      when Array
        s = controller == selected.first && selected.last.split(",").include?(params[:action])
      when Symbol
        s = controller == selected.to_s
      when Hash
        s = true
        selected.keys.each do |i|
          if params[i] != selected[i]
            s = false
            break
          end
        end
        url = url_for(selected)
      when Proc
        s = selected.call
      else
        s = selected
    end

    
    if s
      r = content_tag(:li,content_tag(:span,link_to(text,url)),options)
    else
      r = content_tag(:li,link_to(text,url),options)
    end
    
    if block_given?
      concat(r)
      concat(capture(&block)) if s
    else
      r
    end
  end


  alias fb_tab_item2 link_to_tab

  def facebook_url(*args)
    ([Facebooker.facebooker_config["callback_url"]] + args).join("/")
  end

  def facebook_image_url(*args)
    facebook_url("images",*args)
  end

  def app_url(*args)
    ["http://apps.facebook.com/#{Facebooker.facebooker_config['canvas_page_name']}"].push(args).join("/")
  end

  def a_or_an(name)
    name =~ /^[aouie]/i ? "an" : "a"
  end


def distance_of_time_in_words( from_time, to_time = 0, include_seconds = true )
  from_time = from_time.to_time if from_time.respond_to?(:to_time)
  to_time = to_time.to_time if to_time.respond_to?(:to_time)
  distance_in_minutes = (((to_time - from_time).abs)/60).round
  distance_in_seconds = ((to_time - from_time).abs).round

  case distance_in_minutes
    when 0..1
    case distance_in_seconds
      when 0..59 then "#{pluralize( distance_in_seconds'sec' )}"
      else             "1min"
    end

    when 2..59           then "#{distance_in_minutes}mins"
    when 60              then "1hr"
    when 61..1439        then
      hours, minutes = (distance_in_minutes.to_f / 60.0), (distance_in_minutes.to_f % 60.0)
      "#{pluralize( hours.floor, 'hr' )} #{pluralize(minutes.floor,'mins')}"
    when 1440..1500      then "1day"
    when 1501..2879      then "1day #{pluralize( (distance_in_minutes.to_f / 60 - 24).floor, 'hr' )}"
    when 2880..43199     then "#{(distance_in_minutes / 1440).round}days".gsub(" days","days")
    when 43200..44641    then "1month"
    when 44641..86399    then "1month, #{pluralize( ( distance_in_minutes / 1440 - 30 ).floor, 'day' )}"
    when 86400..525599   then "over #{(distance_in_minutes / 43200).floor}months"
    else                      "over #{pluralize( (distance_in_minutes / 525600).round'years')}"
  end
end

end
